module App::Items
    class Project < Qt::StandardItem
        attr_reader :tid, :name, :billable, :client_name, :client_id

        def self.valid?(togglproject)
            # Clientless projects not supported, I don't use them.
            return true if togglproject["client"]
            return false
        end

        def self.create(model, name, billable, client)
            ret = model.toggl.newProject name, billable, client
            togglproject = ret["content"].first
            new(togglproject)
        end

        def initialize(togglproject)
            super()

            raise "Invalid Toggl Project" unless Project.valid? togglproject

            @tid = togglproject["id"]
            @name = togglproject["name"]
            @billable = togglproject["billable"]
            @client_name = togglproject["client"]["name"]
            @client_id = togglproject["client"]["id"]

            self.setEditable false
            showName
        end

        def destroy
            model.toggl.deleteProject self
            model.deleteProject self
        end

        def save
            model.toggl.setProject self, self.parent
        end

        private
        def showName()
            s = @name.to_s
            s += " $" if @billable
            setText s
        end
    end
end
